import api from '@/utils/api'
import axios from 'axios'

const state = {
  token: localStorage.getItem('token') || null,
  user: JSON.parse(localStorage.getItem('user')) || null,
  loading: false,
  error: null
}

const getters = {
  isAuthenticated: state => !!state.token,
  isAdmin: state => state.user && state.user.role === 'ADMIN',
  isResearcher: state => {
    if (!state.user) return false;
    
    // 打印用户角色信息以便调试
    console.log('用户角色信息:', {
      role: state.user.role,
      roleType: typeof state.user.role,
      roleValue: state.user.role,
      userObject: JSON.stringify(state.user)
    });
    
    // 扩展判断条件，支持多种格式的研究者角色值
    const role = state.user.role;
    
    // 数字格式：1
    if (role === 1) return true;
    
    // 字符串格式："1"
    if (role === '1') return true;
    
    // 枚举字符串格式："RESEARCHER"
    if (typeof role === 'string' && (role.toUpperCase() === 'RESEARCHER')) return true;
    
    // 如果有roleId属性
    if (state.user.roleId === 1 || state.user.roleId === '1') return true;
    
    // 如果有userType属性
    if (state.user.userType === 'researcher' || state.user.userType === 'RESEARCHER') return true;
    
    console.log('用户不是研究者');
    return false;
  },
  currentUser: state => state.user,
  authError: state => state.error,
  authLoading: state => state.loading
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    if (token) {
      localStorage.setItem('token', token)
    } else {
      localStorage.removeItem('token')
    }
  },
  SET_USER(state, user) {
    state.user = user
    if (user) {
      localStorage.setItem('user', JSON.stringify(user))
    } else {
      localStorage.removeItem('user')
    }
  },
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  SET_ERROR(state, error) {
    state.error = error
  },
  CLEAR_ERROR(state) {
    state.error = null
  },
  auth_request(state) {
    state.loading = true
    state.error = null
  },
  auth_success(state, { token, user }) {
    state.loading = false
    state.token = token
    state.user = user
    if (token) {
      localStorage.setItem('token', token)
    } else {
      localStorage.removeItem('token')
    }
    if (user) {
      localStorage.setItem('user', JSON.stringify(user))
    } else {
      localStorage.removeItem('user')
    }
  },
  auth_error(state, error) {
    state.loading = false
    state.error = error
  },
  LOGOUT(state) {
    state.token = null
    state.user = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }
}

const actions = {
  async register({ commit }, credentials) {
    commit('auth_request')
    return new Promise((resolve, reject) => {
      console.log('Registration data:', credentials)
      
      // 确保邮箱字段存在
      const email = credentials.email || `${credentials.username}@example.com`
      
      // 根据选择的角色值设置正确的角色名称
      let roleName = "PARTICIPANT"
      if (credentials.role === 1 || credentials.role === '1') {
        roleName = "RESEARCHER"
      }
      
      console.log('Using role name:', roleName)
      
      // 构建完整的请求对象，确保所有必要字段都存在
      const requestData = {
        username: credentials.username,
        password: credentials.password,
        email: email,
        role: roleName,
        blockchainAddress: credentials.walletAddress || ''
      }
      
      console.log('Sending registration data:', requestData)
      
      // 使用完整的API路径
      axios.post('/auth/register', requestData)
        .then(resp => {
          console.log('Registration success:', resp.data)
          commit('auth_success', { token: resp.data.token, user: resp.data.user })
          resolve(resp)
        })
        .catch(err => {
          const errorMsg = err.response?.data?.message || 'Registration failed'
          console.error('Registration failed:', err.response?.data)
          // 提取验证错误信息
          if (err.response?.data?.errors && err.response.data.errors.length > 0) {
            const validationErrors = err.response.data.errors.map(e => 
              `${e.field || 'Field'}: ${e.defaultMessage || 'Invalid value'}`
            ).join(', ')
            commit('auth_error', `Validation error: ${validationErrors}`)
          } else {
            commit('auth_error', errorMsg)
          }
          reject(err)
        })
    })
  },
  
  async login({ commit }, credentials) {
    commit('auth_request')
    return new Promise((resolve, reject) => {
      console.log('开始登录请求，凭据:', {
        username: credentials.username,
        hasPassword: !!credentials.password
      });
      
      // 使用axios直接发送请求到完整URL
      axios.post('http://localhost:8080/api/medical-crowdsourcing/auth/login', credentials)
        .then(resp => {
          console.log('登录成功响应:', resp.data);
          const token = resp.data.token
          let user = resp.data.user
          
          // 确保用户对象包含角色信息
          if (user) {
            if (!user.role && user.roleId) {
              user.role = user.roleId;
              console.log('从roleId设置角色:', user.role);
            }
            
            // 如果仍然没有角色，设置一个默认角色
            if (!user.role) {
              console.log('设置默认角色为研究者(1)');
              user.role = 1; // 默认设置为研究者
            }
          }
          
          // 添加调试信息
          console.log('处理后的用户数据:', {
            username: user?.username,
            role: user?.role,
            roleId: user?.roleId
          });
          
          localStorage.setItem('token', token)
          axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
          
          commit('auth_success', { token, user })
          resolve(resp)
        })
        .catch(err => {
          console.error('登录失败:', err.response?.data || err.message);
          commit('auth_error', err.response ? err.response.data : 'Login failed')
          localStorage.removeItem('token')
          reject(err)
        })
    })
  },
  
  async fetchUser({ commit, state }) {
    if (!state.token) {
      console.log('没有token，无法获取用户信息');
      return null;
    }
    
    try {
      console.log('开始获取用户信息...');
      
      // 配置请求头，包含授权令牌
      const config = {
        headers: { Authorization: `Bearer ${state.token}` }
      };
      
      // 尝试直接使用axios发送请求到完整URL
      console.log('尝试直接访问完整URL获取用户信息');
      let userData = null;
      let response = null;
      
      try {
        console.log('尝试从完整URL获取用户信息');
        response = await axios.get('http://localhost:8080/api/medical-crowdsourcing/users/me', config);
        userData = response.data;
        console.log('从完整URL获取用户信息成功:', userData);
      } catch (error) {
        console.error('从完整URL获取用户信息失败:', error);
        
        // 尝试从localStorage获取基本用户信息作为备用
        const localUser = JSON.parse(localStorage.getItem('user') || '{}');
        if (localUser && (localUser.role || localUser.username)) {
          console.log('使用localStorage中的用户信息:', localUser);
          commit('SET_USER', localUser);
          return localUser;
        }
        
        throw error;
      }
      
      if (!userData) {
        console.error('获取用户信息失败：返回数据为空');
        
        // 尝试从localStorage获取基本用户信息
        const localUser = JSON.parse(localStorage.getItem('user') || '{}');
        if (localUser && (localUser.role || localUser.username)) {
          console.log('从localStorage获取到用户信息:', localUser);
          commit('SET_USER', localUser);
          return localUser;
        }
        
        return null;
      }
      
      console.log('成功获取到用户数据:', userData);
      
      // 确保用户对象有角色信息
      // 检查各种可能的角色字段
      if (!userData.role) {
        // 尝试从各种可能的字段中提取角色信息
        if (userData.roleId) {
          userData.role = userData.roleId;
        } else if (userData.userRole) {
          userData.role = userData.userRole;
        } else if (userData.userType) {
          // 转换userType到role值
          if (userData.userType === 'RESEARCHER' || userData.userType === 'researcher') {
            userData.role = 1;
          } else if (userData.userType === 'PARTICIPANT' || userData.userType === 'participant') {
            userData.role = 2;
          }
        } else if (userData.type) {
          // 转换type到role值
          if (userData.type === 'RESEARCHER' || userData.type === 'researcher') {
            userData.role = 1;
          } else if (userData.type === 'PARTICIPANT' || userData.type === 'participant') {
            userData.role = 2;
          }
        }
        
        console.log('处理后的用户角色:', userData.role);
      }
      
      // 规范化用户名，确保至少有一个可用的名称字段
      if (!userData.username && !userData.name && !userData.fullName) {
        if (userData.email) {
          // 如果有邮箱，可以提取邮箱前缀作为用户名
          userData.username = userData.email.split('@')[0];
        } else if (userData.id) {
          // 实在没有名称信息，以ID作为标识
          userData.username = `用户${userData.id}`;
        }
      }
      
      // 将用户信息保存到状态中
      commit('SET_USER', userData);
      console.log('用户信息获取成功，已更新状态:', userData);
      
      return userData;
    } catch (error) {
      console.error('获取用户信息错误:', error.response || error);
      
      // 如果是未授权错误（401），清除无效的令牌
      if (error.response && error.response.status === 401) {
        commit('LOGOUT');
      }
      
      // 尝试从localStorage获取基本用户信息作为备用
      const localUser = JSON.parse(localStorage.getItem('user') || '{}');
      if (localUser && (localUser.role || localUser.username)) {
        console.log('API调用失败，使用localStorage中的用户信息:', localUser);
        commit('SET_USER', localUser);
        return localUser;
      }
      
      throw error;
    }
  },
  
  logout({ commit }) {
    // 安全地移除Authorization header
    try {
      if (api && api.defaults) {
        delete api.defaults.headers.common['Authorization']
      }
      if (axios && axios.defaults) {
        delete axios.defaults.headers.common['Authorization']
      }
    } catch (e) {
      console.error('清除授权头信息时出错:', e)
    }
    
    // Clear user data and token
    commit('SET_TOKEN', null)
    commit('SET_USER', null)
  },
  
  async updateProfile({ commit, state }, userData) {
    if (!state.token) throw new Error('Authentication required')
    
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      const response = await api.put('/auth/profile', userData)
      const updatedUser = response.data
      
      commit('SET_USER', updatedUser)
      return updatedUser
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.message || 'Failed to update profile')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async changePassword({ commit, state }, passwordData) {
    if (!state.token) throw new Error('Authentication required')
    
    commit('SET_LOADING', true)
    commit('CLEAR_ERROR')
    try {
      const response = await api.post('/auth/change-password', {
        currentPassword: passwordData.currentPassword,
        newPassword: passwordData.newPassword
      })
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.response?.data?.message || 'Failed to change password')
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 手动设置用户角色(仅用于调试和修复)
  setUserRole({ commit, state }, role) {
    if (!state.user) {
      console.error('没有用户数据，无法设置角色');
      return { success: false, message: '没有用户数据' };
    }
    
    console.log(`手动设置用户角色: ${role}`);
    const updatedUser = { ...state.user, role };
    commit('SET_USER', updatedUser);
    
    return { 
      success: true, 
      message: `已将用户角色设置为: ${role}`,
      user: updatedUser
    };
  },
  
  clearError({ commit }) {
    commit('CLEAR_ERROR')
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
} 